HTMLify
Merge two sorted linked lists.java
Views: 1 | Author: cody
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | // Merge two sorted linked lists java solution //{ Driver Code Starts import java.util.*; class Node { int data; Node next; Node(int d) { data = d; next = null; } } class MergeLists { Node head; /* Function to print linked list */ public static void printList(Node head) { while (head!= null) { System.out.print(head.data+" "); head = head.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { /* Constructed Linked List is 1->2->3->4->5->6-> 7->8->8->9->null */ Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t>0) { int n1 = sc.nextInt(); int n2 = sc.nextInt(); Node head1 = new Node(sc.nextInt()); Node tail1 = head1; for(int i=0; i<n1-1; i++) { tail1.next = new Node(sc.nextInt()); tail1 = tail1.next; } Node head2 = new Node(sc.nextInt()); Node tail2 = head2; for(int i=0; i<n2-1; i++) { tail2.next = new Node(sc.nextInt()); tail2 = tail2.next; } LinkedList obj = new LinkedList(); Node head = obj.sortedMerge(head1,head2); printList(head); t--; } } } // } Driver Code Ends /* Merge two linked lists head pointer input could be NULL as well for empty list Node is defined as class Node { int data; Node next; Node(int d) {data = d; next = null; } } */ class LinkedList { //Function to merge two sorted linked list. Node sortedMerge(Node head1, Node head2) { // This is a "method-only" submission. // You only need to complete this method if(head1 == null){ return head2; } if(head2 == null){ return head1; } Node ans=null; Node t=null; if(head1.data < head2.data){ ans=head1; t=ans; head1=head1.next; }else{ ans=head2; t=ans; head2=head2.next; } while(head1!=null && head2!=null){ if(head1.data < head2.data){ t.next=head1; t=t.next; head1=head1.next; }else{ t.next=head2; t=t.next; head2=head2.next; } } if(head1==null){ t.next=head2; } if(head2==null){ t.next=head1; } return ans; } } |